package main

import (
	"fmt"
	"math"
)

func main() {
	var n int16 = 34
	var m int32
	m = int32(n)
	fmt.Printf("32 bit int is: %d\n", m)
	fmt.Printf("16 bit int is: %d\n", n)

	if fromInt, err := Uint8FromInt(254); err == nil {
		fmt.Println("Uint8FromInt(255) : ", fromInt)
	}

	fromFloat64 := IntFromFloat64(3.1415927)
	fmt.Println("IntFromFloat64(3.1415927) : ", fromFloat64)
}

func Uint8FromInt(n int) (uint8, error) {
	if 0 <= n && n <= math.MaxUint8 { // conversion is safe
		return uint8(n), nil
	}
	return 0, fmt.Errorf("%d is out of the uint8 range", n)
}

func IntFromFloat64(x float64) int {
	// 判断x大于等于Int32位最小的值，并且小于等于Int32位最大的值
	if math.MinInt32 <= x && x <= math.MaxInt32 { // x lies in the integer range
		// math.Modf() 函数，得到 小数点前 和 后的数字，如: 3.14159 分别得到 3 和 0.14159
		whole, fraction := math.Modf(x)
		// 判断 fraction 是否大于等于 0.5 如果大于的话，就四舍五入。
		if fraction >= 0.5 {
			whole++
		}
		return int(whole)
	}
	panic(fmt.Sprintf("%g is out of the int32 range", x))
}
